package com.db.connection;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Properties;

public class DBCPConnectionManager2 {
	private static BasicDataSource ds = null;

	public DBCPConnectionManager2() {
	}


	
	public static void close(Statement pstmt, ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	static {
		if (ds != null) {
			try {
				ds.close();
			} catch (Exception e) {
				//
			}
			ds = null;
		}

		try {
			Properties p = new Properties();
			p.load(DBCPConnectionManager2.class.getResourceAsStream("dbcp2.properties"));
			ds = (BasicDataSource) BasicDataSourceFactory.createDataSource(p);

		} catch (Exception e) {
			//
		}
	}

	public static void init() {

		if (ds != null) {
			try {
				ds.close();
			} catch (Exception e) {
				//
			}
			ds = null;
		}

		try {
			Properties p = new Properties();
			p.load(DBCPConnectionManager2.class.getResourceAsStream("dbcp2.properties"));
			ds = (BasicDataSource) BasicDataSourceFactory.createDataSource(p);

		} catch (Exception e) {
			//
		}
	}

	public static synchronized Connection getConnection() throws SQLException {

		Connection conn = null;
		if (ds != null) {
			conn = ds.getConnection();// ���l��
		}
		conn.setAutoCommit(false);
		return conn;
	}
	
	
	public static void close(Connection conn, Statement pstmt, ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
}
